package com.example.module_mine.helper

import android.os.Handler
import android.os.Looper
import android.view.Gravity.NO_GRAVITY
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import com.example.lib_common.dp
import com.example.module_mine.R
import com.example.module_mine.databinding.LayoutPopupWindowAgreementBinding


/**
 * 弹出窗体
 */
class PopupAgreementHelper(
    private val layoutInflater: LayoutInflater,
) {

    private val mBinding: LayoutPopupWindowAgreementBinding by lazy {
        val binding = LayoutPopupWindowAgreementBinding.inflate(layoutInflater)
        binding.root.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        binding
    }

    private val mPopupWindow by lazy {
        PopupWindow().apply {
            width = ViewGroup.LayoutParams.WRAP_CONTENT
            height = ViewGroup.LayoutParams.WRAP_CONTENT
            isFocusable = true
            isTouchable = false
            animationStyle = R.style.FadeAnim
            contentView = mBinding.root
        }
    }

    fun showAgain(view: View) {
        if (this.mPopupWindow.isShowing) return
        this.showAsDropDown(view)

    }

    fun dismiss() {
        this.mPopupWindow.dismiss()
    }

    /**
     * 在指定控件上方
     */
    private fun showAsDropDown(v: View) {
        val location = IntArray(2)
        v.getLocationOnScreen(location)
        mBinding.root.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        mPopupWindow.showAtLocation(
            v,
            NO_GRAVITY,
            location[0] - 5.dp,
            location[1] - mBinding.root.measuredHeight - 5.dp
        )
        Handler(Looper.getMainLooper()).postDelayed({ this.mPopupWindow.dismiss() }, 1_000)
    }

    fun show(view: View): PopupAgreementHelper {
        if (this.mPopupWindow.isShowing) return this
        this.showAsDropDown(view)
        return this
    }

}